package com.xc.utils;

import java.math.BigDecimal;

/**
 * Created by xc
 */
public class BigDecimalUtil {

//    public int compareTo(BigDecimal val)
//    此方法，如果BigDecimal为小于val返回-1，如果BigDecimal为大于val返回1
//    如果BigDecimal为等于val返回0,
    
    public static BigDecimal add(double v1,double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2);
    }

    public static BigDecimal sub(double v1,double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2);
    }


    public static BigDecimal mul(double v1,double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2);
    }

    public static BigDecimal div(double v1,double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2,2,BigDecimal.ROUND_HALF_UP);//四舍五入,保留2位小数

        //除不尽的情况
    }


    public static double getTwoNum(){
        double num = Math.random();
        double fnum = new BigDecimal(num)
                .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return fnum;
    }


    public static void main(String[] args) {
        System.out.println(BigDecimalUtil.getTwoNum());
    }



}
